#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<iostream>

using namespace std;
int main(){
    /*
     * 1、创建套接字
     * 2、建立连接
     * 3、收发消息
     * */
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        perror("socket");
        return 0;
    }
    //connect
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(22222);
    addr.sin_addr.s_addr = inet_addr("10.0.24.13");

    int ret = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0){
        perror("connect");
        return 0;
    }
    while(1){
        char buf[1024] = {0};
        cout << "please enter your msg#" << endl;
        fflush(stdout);

        cin >> buf;
        int send_size = send(sockfd, buf, strlen(buf), 0);
        if(send_size < 0){
            perror("send");
            continue;
        }
        //接收消息
        memset(buf, '\0', sizeof(buf));
        int recv_size = recv(sockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0){
            perror("send");
            return 0;
        }else if(recv_size == 0){
            //服务端将连接关闭
            cout << "server shutdown connect" << endl;
        }
        printf("%s\n", buf);
    }
    close(sockfd);
    return 0;
}
